package cn.caplike.demo.nio._2021.zerocopy;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Description: IO
 *
 * @author LiKe
 * @version 1.0.0
 * @date 2022-10-06 12:35
 */
public class SocketIO {

    public static class OldServer {

        public static void main(String[] args) throws Exception {
            final ServerSocket serverSocket = new ServerSocket(8899);

            while (true) {
                final Socket socket = serverSocket.accept(); // blocked
                final DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());

                byte[] byteArray = new byte[4096];
                while (true) {
                    final int readCount = dataInputStream.read(byteArray, 0, byteArray.length);
                    if (-1 == readCount) {
                        break;
                    }
                }
            }
        }
    }

    public static class OldClient {
        static String fileName = "<绝对路径>";

        public static void main(String[] args) throws Exception {
            Socket socket = new Socket("127.0.0.1", 8899);

            InputStream inputStream = new FileInputStream(fileName);

            long readCount, total = 0;
            long startTime = System.currentTimeMillis();

            DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
            byte[] buffer = new byte[4096];
            while ((readCount = inputStream.read(buffer)) >= 0) {
                total += readCount;
                dataOutputStream.write(buffer);
            }
            System.out.println("send total: " + total + ", cost: " + (System.currentTimeMillis() - startTime));

            dataOutputStream.close();
            socket.close();
            inputStream.close();
        }
    }
}
